/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatsoft.client.ui;

import ChatSoft.model.ChatMessage;
import ChatSoft.model.ConnectChatVoiceMessage;
import ChatSoft.model.ConnectFileMessage;
import ChatSoft.model.FileMessage;
import ChatSoft.model.FileRequestMessage;
import ChatSoft.model.ServerInfo;
import ChatSoft.model.User;
import ChatSoft.model.VoiceRequestMessage;
import ChatSoft.model.buz.SendObject;
import chatsoft.client.buz.ChatBussiness;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author KID
 */
public class ChatFrame extends javax.swing.JFrame {

    /**
     * Creates new form ChatFrame
     */
    ObjectOutputStream outStream;
    ChatBussiness chatHandle;
    User user;
    String friendName;

    public ChatFrame(ObjectOutputStream outStream, String frName, User user) {
        this.outStream = outStream;
        this.user = user;
        friendName = frName;
        this.setTitle("Chat With " + frName);
        chatHandle = new ChatBussiness(this.outStream);
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtText = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        btnSend = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtMessage = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        btnSend.setIcon(new javax.swing.ImageIcon(getClass().getResource("/chatsoft/client/image/talk.png"))); // NOI18N
        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/chatsoft/client/image/big-smile-icon.png"))); // NOI18N

        txtMessage.setEditable(false);
        txtMessage.setColumns(20);
        txtMessage.setFont(new java.awt.Font("Monospaced", 1, 14)); // NOI18N
        txtMessage.setForeground(new java.awt.Color(255, 0, 0));
        txtMessage.setRows(5);
        jScrollPane2.setViewportView(txtMessage);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/chatsoft/client/image/1351399881_microphone.png"))); // NOI18N
        jButton1.setName("btnVoice"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/chatsoft/client/image/attachment_1.png"))); // NOI18N
        jButton2.setName("btnAttach"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 399, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(21, 21, 21)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(26, 26, 26)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(28, 28, 28)
                                .addComponent(jLabel3)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtText, javax.swing.GroupLayout.PREFERRED_SIZE, 399, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                        .addComponent(btnSend)
                        .addGap(31, 31, 31))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(47, 47, 47)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtText, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    ChatMessage chatMessage;
    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        chatMessage = new ChatMessage();
        chatMessage.setReceiveFrom(user.getUserName());
        chatMessage.setSendTo(friendName);
        chatMessage.setMessage(txtText.getText());
        chatHandle.sendMessage(chatMessage);
        addMessage(txtText.getText(), user.getUserName());
        txtText.setText("");
    }//GEN-LAST:event_btnSendActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        VoiceRequestMessage request = new VoiceRequestMessage();
        request.setReceiveFrom(user.getUserName());
        request.setSendTo(friendName);
        chatHandle.sendVoiceRequest(request);
    }//GEN-LAST:event_jButton1ActionPerformed
    File file;
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.showOpenDialog(this);
        file = fc.getSelectedFile();

        if (file != null) {
            FileRequestMessage request = new FileRequestMessage();
            request.setReceiveFrom(user.getUserName());
            request.setSendTo(friendName);
            chatHandle.sendFileRequest(request);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    public void sendFile(Socket soc, ObjectOutputStream out) throws UnknownHostException, IOException {
        FileMessage con = new FileMessage();
        con.setReceiveFrom(user.getUserName());
        con.setSendTo(friendName);
        SendObject.sendObject(con, out);
        
        
        
        int filesize = 6022386; // filesize temporary hardcoded 

        long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;
        
        // sendfile 
        File myFile = file;
        byte[] mybytearray = new byte[(int) myFile.length()];
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(mybytearray, 0, mybytearray.length);
        OutputStream os = soc.getOutputStream();
        System.out.println("Sending...");
        os.write(mybytearray, 0, mybytearray.length);
        os.flush();
        soc.close();
    }

    public boolean showVerifyBox() {
        return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(null,
                "Bạn có đồng ý tán gẫu bằng giọng nói không",
                "Xác Nhận",
                JOptionPane.OK_CANCEL_OPTION);
    }
    
    public boolean showVerifyFileBox() {
        return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(null,
                "Chấp nhận nhận file!",
                "Xác Nhận",
                JOptionPane.OK_CANCEL_OPTION);
    }

    public void sendConnectVoice(ObjectOutputStream out) {
        ConnectChatVoiceMessage con = new ConnectChatVoiceMessage();
        con.setReceiveFrom(user.getUserName());
        con.setSendTo(friendName);
        SendObject.sendObject(con, out);
    }

    public void sendConnectFile(ObjectOutputStream out) {
        ConnectFileMessage con = new ConnectFileMessage();
        con.setReceiveFrom(user.getUserName());
        con.setSendTo(friendName);
        SendObject.sendObject(con, out);
    }
    
    public void addMessage(String message, String from) {
        txtMessage.append(from + ": " + message + "\n\r");
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSend;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea txtMessage;
    private javax.swing.JTextField txtText;
    // End of variables declaration//GEN-END:variables
}
